<script setup lang="ts">
import { ref, computed } from "vue";
import { useColumns } from "./columns";
import "plus-pro-components/es/components/search/style/css";
import { fixImageUrl, handleImagesUpload } from "@/utils/common";
import UploadIcon from "~icons/ri/upload-2-line?width=26&height=26";
import {
  type Action,
  genFileId,
  ElMessageBox,
  ElMessage,
  UploadInstance,
  UploadProps,
  UploadRawFile
} from "element-plus";
import {
  PlusSearch,
  PlusDialogForm,
  type PlusColumn,
  type FieldValues
} from "plus-pro-components";
import { router } from "@/router";
import { setOrderShip } from "@/api/mall";
defineOptions({
  name: "UserManage"
});

import { useMenu } from "@/utils/power";
const power = useMenu(["info", "ship"]);
const productImageRef = ref<UploadInstance>();

const searchColumns: PlusColumn[] = [
  {
    label: "搜索",
    width: 200,
    prop: "keyWord",
    valueType: "copy",
    tooltip: "请输入搜索关键词"
  },
  {
    label: "开始时间",
    labelWidth: 120,
    width: 600,
    prop: "startTime",
    valueType: "date-picker",
    tooltip: "请选择时间段",
    fieldProps: {
      type: "datetime",
      placeholder: "开始时间",
      format: "YYYY-MM-DD HH:mm:ss",
      valueFormat: "YYYY-MM-DD HH:mm:ss"
    }
  },
  {
    label: "订单状态",
    prop: "orderStatus",
    labelWidth: 120,
    valueType: "select",
    options: [
      {
        label: "全部",
        value: 0,
        color: "red"
      },
      {
        label: "待付款",
        value: 1,
        color: "red"
      },
      {
        label: "待发货",
        value: 2,
        color: "red"
      },
      {
        label: "待收货",
        value: 3,
        color: "red"
      },
      {
        label: "已取消",
        value: 4,
        color: "red"
      },
      {
        label: "已完成",
        value: 5,
        color: "red"
      },
      {
        label: "申请退款",
        value: 7,
        color: "red"
      },
      {
        label: "待填写地址",
        value: 8,
        color: "red"
      }
    ]
  },
  {
    label: "订单编号",
    width: 200,
    labelWidth: 120,
    prop: "no",
    valueType: "input",
    tooltip: "请输入搜索订单号"
  }
];

const defaultSearchState = ref({});

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  onSizeChange,
  loadData,
  onKeywordChange,
  onCurrentChange
} = useColumns();
const columnsRef = computed(() => {
  if (power.value.info || power.value.ship) {
    return columns;
  }
  const columnsCopy = [...columns];
  return columnsCopy.slice(0, -1);
});
function detailClick(row) {
  console.log(
    "%crow===详情>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  router.push({ name: "MallOrderDetail", query: { id: row.id } });
}

const rules = {
  shipCompany: [{ required: true, message: "请输入快递公司", trigger: "blur" }],
  shipNo: [{ required: true, message: "请输入快递单号", trigger: "blur" }],
  shipImage: [{ required: true, message: "请上传订单图片", trigger: "blur" }]
};
const formColumns: PlusColumn[] = [
  {
    label: "快递公司",
    prop: "shipCompany",
    valueType: "input"
  },
  {
    label: "快递单号",
    prop: "shipNo",
    valueType: "input"
  },
  {
    label: "快递凭证",
    prop: "shipImage"
  }
];
const visible = ref(false);
const values = ref<FieldValues>({});
const confirmLoading = ref(false);
function editClick(row) {
  console.log(
    "%crow===编辑>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  values.value = {
    id: row.id
  };
  visible.value = true;
}

const imageFile = (path: any) => {
  return path.split(",").map((path: any) => {
    return { url: fixImageUrl(path), name: path.split("/").pop() };
  });
};
const previewImageUrl = ref();
const previewImageName = ref();
const showPreviewImage = ref(false);

const handleIconImageSuccess: UploadProps["onSuccess"] = (res, file) => {
  values.value.shipImage = res.data;
};
const handleIconImageRemove: UploadProps["onRemove"] = (file, files) => {
  values.value.shipImage = undefined;
};
/// 超出limit限制 先清空文件列表再执行上传
const handleIconImageExceed: UploadProps["onExceed"] = files => {
  productImageRef.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  productImageRef.value?.handleStart(file);
  productImageRef.value?.submit();
};
const handlePreviewImage: UploadProps["onPreview"] = file => {
  previewImageName.value = file.name;
  previewImageUrl.value = file.url;
  showPreviewImage.value = true;
};

const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  console.log("updatedValues", updatedValues);

  confirmLoading.value = true;
  try {
    const res = await setOrderShip(updatedValues);
    visible.value = false;
    confirmLoading.value = false;
    formRef.value?.formInstance?.resetFields();
    ElMessage.success("发货成功");
    loadData();
  } catch (error) {
    confirmLoading.value = false;
    console.log(error, "error");
  }
};

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset", value);
  onKeywordChange(value);
};
const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (target.prop == "keyWord" || target.prop == "no") {
    return;
  }
  onKeywordChange(value);
};
const formRef = ref();
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>订单管理</h3>
        </template>
        <PlusSearch
          :defaultValues="defaultSearchState"
          class="mt-5"
          :columns="searchColumns"
          :hasUnfold="false"
          @reset="handleReset"
          @search="handleSearch"
          @change="handleChange"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columnsRef"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #operation="{ row }">
        <el-button
          v-if="power.info"
          type="info"
          size="small"
          @click="detailClick(row)"
        >
          详情
        </el-button>
        <el-button
          v-if="power.ship"
          :disabled="row.status != 2"
          type="primary"
          size="small"
          @click="editClick(row)"
          >发货</el-button
        >
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      title="填写发货信息"
      @confirm="handleSubmit"
      ><template #plus-field-shipImage>
        <el-upload
          ref="productImageRef"
          drag
          :auto-upload="true"
          list-type="picture-card"
          :limit="1"
          :http-request="handleImagesUpload"
          :file-list="
            values.shipImage && values.shipImage.length > 0
              ? imageFile(values.shipImage)
              : []
          "
          :on-success="handleIconImageSuccess"
          :on-remove="handleIconImageRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleIconImageExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template></PlusDialogForm
    >
    <el-dialog v-model="showPreviewImage">
      <img w-full :src="previewImageUrl" :alt="previewImageName" />
    </el-dialog>
  </ElCard>
</template>

<style scoped></style>
